<template>
  <div class="ding-message">
    <div v-if="isShowBtn" class="ding-message-btn" @click="showDialog">发起飞书任务</div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="true"
      :class="{'mobile-el-dialog':showMobilePage}"
      class="order-setting-dialog small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title title="新建飞书任务通知" font-size="16px" style="margin-bottom: 32px;" />
        <el-form
          ref="orderForm"
          :rules="rules"
          label-position="left"
          label-width="70px"
          class="setting-form lineHeight32">
          <el-form-item label="接收人" prop="userId" style="margin-bottom: 24px;">
            <!-- 选择部门，多选 -->
            <!-- <el-cascader
              v-if="dialogVisible"
              ref="ding-cascader"
              v-model="userId"
              :show-all-levels="false"
              :options="deptList"
              :props="cascaderProps"
              class="ding-user-select"
              popper-class="ding-user-select"
              collapse-tags
              size="small"
              clearable/> -->
            <el-cascader
              v-select-scroll
              v-if="dialogVisible"
              ref="ding-cascader"
              v-model="userId"
              :disabled="optionsChanged"
              :show-all-levels="false"
              :options="allDeptList"
              :props="allCascaderProps"
              class="ding-user-select multiply-select-scroll"
              popper-class="ding-user-select"
              size="small"
              clearable
              filterable
              style="width:240px;"
              @change="cascaderChanage"
            >
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.value.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.value }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.value }}</span>
                </el-tooltip>
                <span v-else>{{ data.value }}</span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="任务描述" prop="content" style="margin-bottom: 24px;">
            <el-input
              :rows="3"
              v-model="content"
              resize="none"
              style="font-size: 13px;"
              type="textarea"
              maxlength="200"
              placeholder="请输入内容"/>
          </el-form-item>
        </el-form>
      </div>
      <div class="feishu-btn-container">
        <el-button :loading="loading" type="primary" size="small" @click="sendMessasge()">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 该组件用于发送钉钉消息
 */
import { sendFeishuTalk } from '@/api/login';
import ElMessage from '@/utils/message';
import Title from '@/components/Title';
import { getList } from '@/api/user';
import { deptList, allDeptlist } from '@/api/select';
import { getDepartmentUser } from '@/api/auth';
import { handelDepartmentData, getDepartmentTreePath } from '@/utils';
import { mapState } from 'vuex';
export default {
  name: 'DingTalkSend',
  components: { Title },
  props: {
    isShowBtn: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const that = this;
    return {
      rules: {},
      content: '',
      userId: [],
      dialogVisible: false,
      optionsChanged: true,
      loading: false,
      userList: [],
      defaultUserId: [],
      deptList: [],
      allDeptList: [],
      userLoading: false,
      allCascaderProps: {
        multiple: true,
        value: 'id',
        label: 'value'
      },
      cascaderProps: {
        multiple: true,
        lazy: true,
        value: 'id',
        label: 'value',
        lazyLoad(node, resolve) {
          const { level } = node;
          if (level < 2 && !node.root && node.data) {
            const params = { id: node.data.id };
            getDepartmentUser(params).then(res => {
              handelDepartmentData(res.data);
              resolve(res.data);
              if (res.data.length === 0) {
                that.setDisabled(params.id);
              }
            });
          } else {
            resolve();
          }
        }
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    cascaderChanage(value) { // 选中节点发生变化的时候
      localStorage.setItem('ddTalkNotification', JSON.stringify(value));
    },
    showDialog() {
      // this.getDeptList();
      this.getAllDeptList();
      const initData = JSON.parse(localStorage.getItem('ddTalkNotification'));
      if (initData && initData.length > 0) {
        this.userId = initData;
      }
      this.dialogVisible = true;
    },
    hasDefaultShowDialog(defaultUserId, resourceName = '') {
      this.defaultUserId = defaultUserId;
      this.content = resourceName;
      this.getAllDeptList();
      this.dialogVisible = true;
    },
    async sendMessasge() {
      if (!this.userId || this.userId.length <= 0) {
        ElMessage.warning('请选择接收人');
        return;
      }
      let userIds = [];
      if (this.userId.length > 0) {
        userIds = this.userId.map(i => {
          if (i.length > 1) return i[i.length - 1];
        }).filter(i => !!i);
      }
      if (!this.content || this.content === '') {
        ElMessage.warning('请输入任务描述');
        return;
      }
      if (this.content.length < 3 || this.content.length > 200) {
        ElMessage.warning('请输入3~200字的任务描述');
        return;
      }
      try {
        const params = {
          // url: '/#' + this.$route.path,
          url: `${location.origin}?redirect=${this.$route.fullPath}`,
          content: this.content,
          userId: userIds
        };
        this.loading = true;
        const result = await sendFeishuTalk(params);
        this.loading = false;
        if (result.code === 200) {
          this.$message.success('发送成功');
          this.handleClose(true);
        } else {
          this.$message.error(result.message);
        }
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
    },
    handleClose(reset = false) {
      this.dialogVisible = false;
      if (reset) {
        this.deptList = [];
        this.userId = [];
        this.content = '';
        this.defaultUserId = [];
      }
    },
    loadmore() {
      const userList = this.userList;
      const currentPage = userList.page;
      if (userList.items) {
        const isMax = userList.items.length >= userList.total;
        if (!isMax && !this.userLoading) {
          this.getUser(currentPage + 1, '');
        }
      }
    },
    filterData(val) {
      this.getUser(1, val);
    },
    // 获取用户列表
    getUser(page = 1, userName = '') {
      this.userLoading = true;
      getList(page, 15, { userName }).then(({ data }) => {
        this.userLoading = false;
        if (page > 1 && this.userList.items) {
          const concatList = this.userList.items.concat(data.items);
          data.items = concatList;
        }
        this.userList = data;
      });
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data);
        this.allDeptList = res.data;
        this.optionsChanged = false;
        if (this.defaultUserId.length) {
          const userIds = [];
          for (let i = 0; i < this.allDeptList.length; i++) {
            const item = getDepartmentTreePath(this.allDeptList[i]);
            if (userIds.length === this.defaultUserId.length) {
              return;
            } else {
              for (let d = 0; d < item.length; d++) {
                const itemD = item[d];
                const itemLength = itemD.length === 0 ? 0 : itemD.length;
                const lastItem = itemD[itemLength - 1];
                if (this.defaultUserId.indexOf(lastItem) >= 0) {
                  userIds.push(itemD);
                }
              }
              if (userIds.length > 0) {
                this.userId = userIds;
              }
            }
          }
        }
      });
    },
    getDeptList() {
      deptList().then(res => {
        res.data.forEach(i => { i.disabled = false; });
        this.deptList = res.data;
      }, result => {
        // this.$message({
        //   type: 'error',
        //   message: result.message
        // });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.ding-message {
  .ding-message-btn {
    // position: fixed;
    // z-index: 1990;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
    cursor: pointer;
  }
  .setting-form {
    &::v-deep {
      .el-form-item__label {
        color: #666;
      }
    }
  }

  .ding-user-select {
    height: 32px;
    width: 240px;
    &::v-deep {
      .el-input {
        height: 32px;
        width: 240px;
        .el-input__inner {
          height: 32px !important;
          width: 240px;
        }
        .el-input__suffix {
          display: flex;
          align-items: center;
        }
      }
      .el-tag--info {
        color: #406EFF;
        background-color: #ecf1ff;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
.order-setting-dialog {
  &::v-deep {
    .el-dialog {
      border-radius: 12px;
      .el-textarea__inner {
        width: 240px;
      }
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
.feishu-btn-container {
  display: flex;
  justify-content: center;
  .empty {
    flex: 1;
  }
  & ::v-deep {
    .el-button--small {
      width: 120px;
      height: 32px;
      background: #406EFF;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
      color: #FFFFFF;
      line-height: 16px;
    }
  }
}
</style>

<style lang="scss">
.ding-user-select {
  .el-tag {
    color: #406eff;
    background-color: #eff3fb;
  }
  .el-cascader-menu__wrap {
    height: 300px !important;
  }
}
</style>
